LeetCode Js-119. Pascal's Triangle II
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
給予一個整數 rowIndex,回傳 Pascal 三角形的第 rowIndex-th行。
ex.在 Pascal 三角形中,每個數字都是正上方的兩個數字之和。
- rowIndex = 5
- array-1th = [1]
- array-2th = [1,1]
- array-3th = [1,2,1]
- array-4th = [1,3,3,1]
- array-5th = [1,4,6,4,1]
Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]
Solution:
i = V
previous = O
current = #
#
array-2th = [1,1] ->j
array-3th = [1,2,1] ->i
O V
Code:
var getRow = function(rowIndex) {
if (rowIndex === 0) return [1]
if (rowIndex === 1) return [1,1]
let array = [1]
for (let i = 1; i <= rowIndex; i++) {
let previous = array[i - 1]
for (let j = 1; j < i; j++) {
let current = array[j] ? array[j] : 0
array[j] = previous + current
previous = current
}
array.push(1)
}
return array
};
FlowChart:
Example 1
Input: rowIndex = 3
let array = [1]
step.1
i = 1, j = 1
previous = array[1-1] = array[0] = 1
array.push(1) = [1] => [1,1]
step.2
i = 2, j = 1
previous = array[2-1] = array[1] = 1
step.2-1
i = 2, j = 1
current = array[1] ? array[1] : 0 => 1 //array[1] = 1
array[1] = previous + current = 1 + 1 //2
previous = current //1
array.push(1) = [1] => [1,2,1]
step.3
i = 3, j = 1
previous = array[3-1] = array[2] = 1
step.3-1
i = 3, j = 1
current = array[1] ? array[1] : 0 => 2 //array[1] = 2
array[1] = previous + current = 1 + 2 //3
previous = current //1
step.3-2
i = 3, j = 2(j < 3)
current = array[2] ? array[2] : 0 => 2 //array[2] = 2
array[2] = previous + current = 1 + 2 //3
previous = current //1
array.push(1) = [1] => [1,3,3,1]
return array //[1,3,3,1]